package com.example.phongtrinhb2;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText txta=(EditText)findViewById(R.id.text_a);
        final EditText txtb=(EditText)findViewById(R.id.text_b);
        final EditText txtc=(EditText)findViewById(R.id.text_c);
        
        final TextView solution_a=(TextView)findViewById(R.id.solution_a);
        final TextView solution_b=(TextView)findViewById(R.id.solution_b);
        
        final Button button=(Button)findViewById(R.id.button_solve);
        
        button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try{
					double a=Double.parseDouble(txta.getText().toString());
					double b=Double.parseDouble(txtb.getText().toString());
					double c=Double.parseDouble(txtc.getText().toString());
					
					if(a<0){
						a*=-1;
						b*=-1;
						c*=-1;
					}
					
					double d=b*b-4*a*c;
					String sol1="",sol2="";
					if(d>0){
						sol1="Solution 1 is " + ((-b+Math.sqrt(d))/2/a);
						sol2="Solution 2 is " + ((-b-Math.sqrt(d))/2/a);
					}else if(d==0){
						sol1="Solution : " + (-b/2/a);
					}else{
						sol1="Solution 1 is " + (-b/2/a)+"+"+(Math.sqrt(-d)/2/a)+"i";
						sol2="Solution 1 is " + (-b/2/a)+"-"+(Math.sqrt(-d)/2/a)+"i";
					}
					solution_a.setText(sol1);
					solution_b.setText(sol2);
				}catch(Exception ex){
					AlertDialog.Builder builder=new Builder(MainActivity.this);
					builder.setMessage("Please enter all fields");
					builder.setTitle("Infor missing");
					builder.setPositiveButton("Ok",null);
					builder.show();
				}
			}
		});
        final Button btClear=(Button)findViewById(R.id.button_clear);
        btClear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				txta.setText("0");
				txtb.setText("0");
				txtc.setText("0");
				solution_a.setText("");
				solution_b.setText("");
			}
		});
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
